/**
 * @description:
 * @file: user.ts
 * @author: Evan
 * @date: 2025.04.09 14:41:49
 * @week: 周三
 * @version: V
 * */

import { defineStore } from 'pinia'
import {
  getSession,
  setSession,
  removeSession,
  getStorage,
  setCookie,
  getCookieAndSearch,
  setStorage
} from '@/utils/storage'
import { getSearchParams } from '@/utils/win'

import { resetRouter } from '@/router'
import { useAppStore } from './app'
import { separator } from './auth'
import { request } from '@/api'

import type { UserStore } from './type'

// 缓存 key
const tokenKey = 'app_token'
const projectkey = 'app_projId'

// 获取 token
const params = getSearchParams()
const cookie = getCookieAndSearch()
const token =
  import.meta.env.VITE_MODE === '-dev'
    ? params[tokenKey] || cookie[tokenKey] || getSession(tokenKey)
    : ''

const projectId = getStorage(projectkey) || (import.meta.env.VITE_MODE === 'dev' ? '75501' : '')

const userStore: UserStore = {
  token: token !== 'undefined' ? token : '',
  showAvatar: true,

  userInfo: {
    id: '',
    name: '',
    account: '',
    avatar: ''
  },

  powers: [], // 权限列表
  // 默认项目
  projectId: projectId !== 'undefined' ? projectId : '',
  projects: [], // 项目
  projectName: ''
}

const env = import.meta.env

export const useUserStore = defineStore('user', {
  state: () => userStore,

  actions: {
    // 登录
    login(
      params: Parameters<typeof request.login>[0],
      loading: Parameters<typeof request.login>[1]
    ) {
      return request.login(params, loading).then(res => {
        const { access_token } = res
        this.token = access_token
        setSession(tokenKey, access_token)
        return res
      })
    },

    // 获取用户信息
    async getUserInfo() {
      const data = await request.getUserInfo()

      // 更新权限 用户信息
      this.$patch({
        userInfo: {
          id: data.id,
          name: data.realName,
          account: data.username,
          avatar: data.avatar
        }
      })

      await this.getProjectDetail()

      const { permissions, modules, menuList } = await this.getUserAuth()

      const appStore = useAppStore()
      // 模块列表
      appStore.updateModules(modules, menuList)

      // 切换项目开关
      if (appStore.changeProjectSwitch) {
        this.getAuthProjectList()
      }

      this.powers = permissions

      return this.powers
    },

    // 获取项目详情
    async getProjectDetail() {
      return request.getProjectDetail(this.projectId).then(res => {
        let logo = res.logo
        let logoSmall = res.logoSmall

        this.projectName = res.name

        // 更新logo
        const appStore = useAppStore()
        appStore.updateLogo({
          normal: logo,
          small: logoSmall
        })
        return res
      })
    },

    // 获取用户权限
    async getUserAuth() {
      return request.getUserAuth().then(list => {
        const appStore = useAppStore()

        const modules = list.map(item => {
          return {
            ...item,
            sort: item.order,
            //	类型 0：菜单 1：模块 2：标签页 3：按钮
            type: 1
          }
        })

        // 当前系统菜单列表
        const menuList = modules.find(item => item.code === appStore.module.current)?.children || []

        // 获取所有菜单权限编码
        const findMenuCode = (
          menus: Awaited<ReturnType<typeof request.getUserAuth>>,
          list: string[]
        ) => {
          menus.forEach(item => {
            list.push(item.code + separator + item.order)
            findMenuCode(item.children || [], list)
          })
          return list
        }

        const model = import.meta.env.VITE_MODE
        // 不同环境下默认权限, 不可为空，权限判断时长度为 0 会一直请求
        const defaultPowers =
          model == 'dev' ? ['DEV', 'TEST'] : model == 'test' ? ['TEST'] : ['NO_SN']
        // 权限限制
        const pageAuth = this.userInfo.account == 'test' ? 'AUTH' : 'AUTH'
        if (pageAuth) {
          defaultPowers.push(pageAuth)
        }
        const permissions = findMenuCode(menuList, defaultPowers)

        return {
          permissions,
          modules,
          menuList
        }
      })
    },

    // 查询权限项目列表
    getAuthProjectList() {
      request.getUserAuthProjects().then(list => {
        this.projects = list.map(item => {
          return {
            ...item,
            name: item.name,
            code: item.id as string
          }
        })
      })
    },

    // 更新项目 id
    updateProjectId(id: string) {
      setStorage(projectkey, id)
      this.projectId = id
    },

    // 清除缓存
    clearStore() {
      this.$patch({
        token: void 0,
        powers: []
      })
      removeSession(tokenKey)
      setCookie(tokenKey, '', -1)
    },

    // 退出登录
    logout() {
      return request.logout().then(res => {
        this.clearStore()
        resetRouter()
        return res
      })
    },

    // 跳转登录-单点登录界面
    jumpLoginPage() {
      let loca = window.location
      // 跳转根目录
      if (env.VITE_MODE == 'dev') {
        const key = 'CIE_REPEAT_LOGIN'
        const str = getSession(key) || ''
        const arr = str.split(key)
        const t = Number(arr[0]) || 0
        let c = Number(arr[1]) || 0
        const ts = Date.now()
        // 间隔时间大于 1000 毫秒 次数小于 2
        if (ts - t > 1000 && c < 2) {
          c++
          const str = ts + key + c
          setSession(key, str)
          window.location.href = loca.origin
        } else {
          const str = t + key + 0
          setSession(key, str)
        }
        return
      }
      let locationUrl = `${loca.href.split('#')[0]}`
      // 跳转根目录
      window.location.href = `/?redirect_uri=${locationUrl}`
    },

    // 重置token
    resetToken(onlyReset?: Boolean) {
      return new Promise((resolve: Function) => {
        this.clearStore()
        resetRouter()

        if (!onlyReset) {
          this.jumpLoginPage()
        }
        resolve()
      })
    }
  }
})
